<?php
namespace App\Http\Controllers\Home;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\Request;

/**
 * Description of PersonController
 *
 * @author Administrator
 */
class PayController extends \App\Http\Controllers\Controller {
    
    public function index($id) {
        //初始化日志
        $order = \App\Models\Order::where('status', 0)->find($id);
        if(!$order) {
            return redirect('home/index/index');
        }
        $logHandler= new \CLogFileHandler(app_path().'/../public/paylog/'.date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);
        //①、获取用户openid
        $tools = new \JsApiPay();
        $openId = session('home')->openid;//$order->strGetOpenId();//支付人的openid与当前登录用户的openid相同
		$price = $order->orderPrice();
        $total_fee = $price * 100;   //总支付金额
        //如果是代付订单设置代付人id
        if(session('home')->phone == $order->payphone) {
            $attach = session('home')->id;
        } else {
            $attach = '';
        }
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("{$order->strProduct()}");
        $input->SetAttach("{$attach}");
        $input->SetOut_trade_no("{$order->order}");
        $input->SetTotal_fee($total_fee);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        //$input->SetGoods_tag("test");
        $input->SetNotify_url(url('home/pay/notify'));
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $orderes = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($orderes);
		$order->issub = 1;
		$order->save();
		$assign = compact('jsApiParameters', 'id');
        return view('home.pay.pay', $assign);
    }
    /**
     * 回调通知接口
     */
    public function notify() {
		$logHandler= new \CLogFileHandler(app_path().'/../public/paylog/'.date('Y-m-d').'.log');
		$log = \Log::Init($logHandler, 15);
        \Log::DEBUG("流程开始");
        $notify = new PayNotifyController();
        $notify->Handle(false);
    }
    
    /**
     * 支付结果显示接口
     * @param type $id
     */
    public function result($id) {
        $order = \App\Models\Order::find($id);
        $assign = compact('order');
        return view('home.pay.result', $assign);
    }
}
